package com.BinarySheep.eTools;

import java.text.DecimalFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Calcs extends Activity {
	
	private int calcMode =0;
	
	// Handles
	private Spinner mCalcMode = null;	
	private RelativeLayout mRow1 = null;
	private RelativeLayout mRow2 = null;
	private RelativeLayout mRow3 = null;	
	private TextView mLabel1 = null;
	private TextView mLabel2 = null;
	private TextView mLabel3 = null;
	private EditText mInput1 = null;
	private EditText mInput2 = null;
	private EditText mInput3 = null;
	private TextView mUnit1 = null;
	private TextView mUnit2 = null;
	private TextView mUnit3 = null;
	private TextView mResult = null;
	private ImageView mFormula = null;

	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calcs);
        
        // Get handles
        mCalcMode = (Spinner)findViewById(R.id.calcmode);
        mRow1 = (RelativeLayout)findViewById(R.id.row1);
        mRow2 = (RelativeLayout)findViewById(R.id.row2);
        mRow3 = (RelativeLayout)findViewById(R.id.row3);
        mLabel1 = (TextView)findViewById(R.id.label1);
        mLabel2 = (TextView)findViewById(R.id.label2);
        mLabel3 = (TextView)findViewById(R.id.label3);        
        mInput1 = (EditText)findViewById(R.id.input1);
        mInput2 = (EditText)findViewById(R.id.input2);
        mInput3 = (EditText)findViewById(R.id.input3);        
        mUnit1 = (TextView)findViewById(R.id.unit1);
        mUnit2 = (TextView)findViewById(R.id.unit2);
        mUnit3 = (TextView)findViewById(R.id.unit3);
        mResult = (TextView)findViewById(R.id.result);
        mFormula = (ImageView)findViewById(R.id.formula);
        
        // Attach handler to text inputs
        mInput1.setOnKeyListener(textInputHandler);
        mInput2.setOnKeyListener(textInputHandler);
        mInput3.setOnKeyListener(textInputHandler);
        
        // Populate mCalcMode spinner
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
        		this, R.array.calcmodes, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mCalcMode.setAdapter(adapter);
        mCalcMode.setOnItemSelectedListener(spnCalcModeListener);
	}	
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu_led, menu);
    	return result;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.tools:
    		finish();
    		return true;
    	case R.id.about:
    		showAbout();
    		return true;
    	case R.id.help:
    		showHelp();
    		return true;
    	}
    	return super.onOptionsItemSelected(item);
    }
    
    protected void showHelp() {
        View messageView = getLayoutInflater().inflate(R.layout.help_resistor, null, false);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.help_resistor_title);
        builder.setView(messageView);
        builder.setPositiveButton("Done", null);
        builder.create();
        builder.show();
    }
    
    protected void showAbout() {
        // Inflate the about message contents
        View messageView = getLayoutInflater().inflate(R.layout.about, null, false);
        
        // When linking text, force to always use default color. This works
        // around a pressed color state bug.
        TextView textView = (TextView) messageView.findViewById(R.id.about_credits);
        int defaultColor = textView.getTextColors().getDefaultColor();
        textView.setTextColor(defaultColor);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.icon);
        builder.setTitle(R.string.app_name_short);
        builder.setView(messageView);
        builder.setPositiveButton("Done", null);
        builder.create();
        builder.show();
    }
	
    // Input TextView handler
    private View.OnKeyListener textInputHandler =
    	new View.OnKeyListener() {
    	public boolean onKey(View v, int keyCode, KeyEvent event) {
    		switch(calcMode) {
    		case 0:
    			calc_LED();
    			break;    		
    		case 1:
    			calc_InductReact();
    			break;    		
    		case 2:
    			calc_CapReact();
    			break;    		
    		}    		
			return false;
    	}
    };
    
    // mCalcMode Spinner handler
	private Spinner.OnItemSelectedListener spnCalcModeListener =
		new Spinner.OnItemSelectedListener() {
		public void onItemSelected(AdapterView parent, View v, int position, long id) {
			// Update UI based on selected spinner item			
			calcMode = parent.getSelectedItemPosition();
			switch(calcMode) {
			case 0:
				calcUI_LED();
				break;
			case 1:
				calcUI_InductReact();
				break;
			case 2:
				calcUI_CapReact();
				break;
			}
		}
		public void onNothingSelected(AdapterView parent) { }
	};
		
	// LED/Resistor calc UI
	private void calcUI_LED() {
		// Row1: Source Voltage (V)
		mRow1.setVisibility(View.VISIBLE);
		mLabel1.setText("Source Voltage:");
		mUnit1.setText("V");
		
		// Row2: Diode Forward Voltage (V) 
		mRow2.setVisibility(View.VISIBLE);		
		mLabel2.setText("Forward Voltage:");
		mUnit2.setText("V");
		
		// Row3: Diode Forward Current (mA)
		mRow3.setVisibility(View.VISIBLE);		
		mLabel3.setText("Forward Current:");
		mUnit3.setText("mA");
		
		// Formula Image
		mFormula.setImageResource(R.drawable.form1);
		
		// Do first calc
		calc_LED();
	}
	
	// LED/Resistor Calculator
	private void calc_LED() {		
		double Vsrc;
		double Vdiode;
		double Idiode;
		
		// Conversion
		try {
			Vsrc = Double.parseDouble(mInput1.getText().toString());
			Vdiode = Double.parseDouble(mInput2.getText().toString());
			Idiode = Double.parseDouble(mInput3.getText().toString());
			// Idiode is in mA
			Idiode *= 0.001;
		} catch (NumberFormatException e) {
			mResult.setText("invalid");
			return;
		}
		
		// Input tests
		if (Vdiode > Vsrc) {
			mResult.setText("Vdiode > Vsrc");
			return;
		}

		// Calculation: R = (Vsrc - Vdiode) / Idiode 
		double result = (Vsrc - Vdiode) / Idiode;
		
		// Result
		DecimalFormat df = new DecimalFormat("0.0");
		mResult.setText("R = " + df.format(result) + "\u2126");
	}

	// Inductive Reactance calc UI
	private void calcUI_InductReact() {
		// Row1: Frequency (f-Hz)
		mRow1.setVisibility(View.VISIBLE);
		mLabel1.setText("Frequency:");
		mUnit1.setText("f-Hz");
		
		// Row2: Inductance (L-mH)
		mRow2.setVisibility(View.VISIBLE);		
		mLabel2.setText("Inductance:");
		mUnit2.setText("L-mH");

		// Row3: Hidden
		mRow3.setVisibility(View.GONE);		

		// Formula Image
		mFormula.setImageResource(R.drawable.form2);
		
		// Do first calc
		calc_InductReact();
	}
	
	// Inductive Reactance Calculator
	private void calc_InductReact() {		
		double freq;
		double induct;
		
		// Conversion
		try {
			freq = Double.parseDouble(mInput1.getText().toString());
			induct = Double.parseDouble(mInput2.getText().toString());
			// Inductance is in mH
			induct *= 0.001;
		} catch (NumberFormatException e) {
			mResult.setText("invalid");
			return;
		}

		// Calculation: X = 2 * pi * f * I
		double result = 2 * Math.PI * freq * induct;
		
		// Result
		DecimalFormat df = new DecimalFormat("0.00");
		mResult.setText(df.format(result) + "\u2126");
	}
	
	// Capacitive Reactance calc UI
	private void calcUI_CapReact() {
		// Row1: Frequency (f-Hz)
		mRow1.setVisibility(View.VISIBLE);
		mLabel1.setText("Frequency:");
		mUnit1.setText("f-Hz");
		
		// Row2: Inductance (L-mH)
		mRow2.setVisibility(View.VISIBLE);		
		mLabel2.setText("Capacitance:");
		mUnit2.setText("C-\u00B5F");

		// Row3: Hidden
		mRow3.setVisibility(View.GONE);
		
		// Formula Image
		mFormula.setImageResource(R.drawable.form3);
		
		// Do first calc
		calc_CapReact();
	}
	
	// Capacitive Reactance Calculator
	private void calc_CapReact() {		
		double freq;
		double cap;
		
		// Conversion
		try {
			freq = Double.parseDouble(mInput1.getText().toString());
			cap = Double.parseDouble(mInput2.getText().toString());
			// Capacitance is in uF
			cap *= 0.000001;
		} catch (NumberFormatException e) {
			mResult.setText("invalid");
			return;
		}

		// Calculation: X = 1 / ( 2 * pi * f * C )
		double result = 1 / (2 * Math.PI * freq * cap);
		
		// Result
		DecimalFormat df = new DecimalFormat("0.00");
		mResult.setText(df.format(result) + "\u2126");
	}
	
}
